/**
 * 
 */
package com.sys.object.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

import com.sys.object.common.context.Config;

/**
 * 
 *
 */
public class FileUtil {
	
	/**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        if (".xlsx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }
        if (".xls".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-excel";
        }
        //默认返回类型
        return "image/jpeg";
    }

	/**
	 * 以文件形式来上传图片
	 * 
	 * @param file
	 * @param ext
	 * @return
	 */
	public synchronized byte[] getFileContent(File file) {
		try {

			Long filelength1 = file.length();
			byte[] filecontent = new byte[filelength1.intValue()];
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
			return filecontent;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String string(byte[] data, String filename) {
		try{
			String root = Thread.currentThread().getContextClassLoader().getResource("").toString().replaceAll("file:", "").replaceAll("WEB-INF/classes/", "upload/");
			String savePath = Config.getConfigValue("loadpath").trim();
			if (!StringUtils.hasText(savePath)) {
				savePath = root;
			}
			String saveUrl = Config.getConfigValue("saveurl").trim() + "upload/";
			// 创建文件夹
			String dirName = "image";
			savePath += dirName + "/";
			saveUrl += dirName + "/";
			System.out.println(savePath);
			//savePath += DateUtils.getYearMothDateFolder() + "/";
			//saveUrl += DateUtils.getYearMothDateFolder() + "/";
			createDir(savePath);
			File dirFile = new File(savePath + "" + filename);
			if (!dirFile.exists()) 
				dirFile.createNewFile();
				
			FileUtil.byte2file(data, savePath + "" + filename);
	
			return saveUrl + filename;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public static String uploadApp(byte[] data, String filename) {
		try{
			String root = Thread.currentThread().getContextClassLoader().getResource("").toString().replaceAll("file:", "").replaceAll("WEB-INF/classes/", "upload/");
			String savePath = Config.getConfigValue("loadpath").trim();
			if (!StringUtils.hasText(savePath)) {
				savePath = root;
			}
			String saveUrl = Config.getConfigValue("saveurl").trim() + "upload/";
			// 创建文件夹
			String dirName = "app";
			savePath += dirName + "/";
			saveUrl += dirName + "/";
			
			//savePath += DateUtils.getYearMothDateFolder() + "/";
			//saveUrl += DateUtils.getYearMothDateFolder() + "/";
			createDir(savePath);
			File dirFile = new File(savePath + "" + filename);
			if (!dirFile.exists()) 
				dirFile.createNewFile();
			FileUtil.byte2file(data, savePath + "" + filename);
	
			return saveUrl + filename;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	// byte数组到图片
	public static synchronized boolean byte2image(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return false;
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
			return true;
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
		}
		return false;
	}

	// byte数组到图片
	public static synchronized boolean byte2file(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return false;
		try {
			FileOutputStream fos = new FileOutputStream(new File(path));
			fos.write(data);
			fos.flush();
			fos.close();
			return true;
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
		}
		return false;
	}

	public static boolean createDir(String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			makeDir(file.getParentFile());
		}
		return file.mkdir();
	}

	public static void makeDir(File dir) {
		if (!dir.getParentFile().exists()) {
			makeDir(dir.getParentFile());
		}
		dir.mkdir();
	}
	
	public static String testImage(byte[] data, String filename) {
		try{
			String savePath = "/data/";
			String dirName = "image";
			savePath += dirName + "/";
			System.out.println(savePath);
			createDir(savePath);
			File dirFile = new File(savePath + "" + filename);
			if (!dirFile.exists()) 
				dirFile.createNewFile();
				
			FileUtil.byte2file(data, savePath + "" + filename);
	
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
